package quantity.trande

import cn.hutool.core.date.DateUtil
import cn.hutool.core.util.RandomUtil
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONPath
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.sse.EventSource
import okhttp3.sse.EventSourceListener
import okhttp3.sse.EventSources.createFactory
import quantity.trande.util.executeInsert
import java.math.BigDecimal
import java.nio.charset.StandardCharsets
import java.util.*
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit


val CLIENT = OkHttpClient.Builder()
    .callTimeout(3, TimeUnit.SECONDS)
    .build()
fun main() {
    val newScheduledThreadPool = Executors.newScheduledThreadPool(12)
    newScheduledThreadPool.scheduleAtFixedRate({
        val randomDouble = RandomUtil.randomDouble(0.0, 1.0)
        val request = Request.Builder()
            .get()
            .url("https://api-q.fx678img.com/getQuote.php?exchName=NYMEX&symbol=CONC&st=$randomDouble")
            .header("Accept", "application/json, text/javascript, */*; q=0.01")
            .header("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6")
            .header("Connection", "keep-alive")
            .header("Host", "api-q.fx678img.com")
            .header("Origin", "https://quote.fx678.com")
            .header("Referer", "https://quote.fx678.com/")
            .header("sec-ch-ua", """"Microsoft Edge";v="107", "Chromium";v="107", "Not=A?Brand";v="24"""")
            .header("sec-ch-ua-mobile", "?0")
            .header("sec-ch-ua-platform", """"macOS"""")
            .header("Sec-Fetch-Dest", """empty""")
            .header("Sec-Fetch-Mode", """cors""")
            .header("Sec-Fetch-Site", """cross-site""")
            .header(
                "User-Agent",
                """Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.42"""
            )
            .build()
        val response = CLIENT.newCall(request).execute()
        response.body?.bytes()?.let {
            try {
                val content = String(it, StandardCharsets.UTF_8)
                val parseObject = JSON.parseObject(content)
                val nowPrice = JSONPath.eval(parseObject, "$.se[0]") as String
                val updateTime = JSONPath.eval(parseObject, "$.t[0]") as String
                val time = DateUtil.format(
                    DateUtil.calendar(updateTime.toLong() * 1000).time, "yyyy-MM-dd HH:mm:ss"
                )
                val now = DateUtil.format(Date(), "yyyy-MM-dd HH:mm:ss")
                executeInsert(
                    """
                insert into trade_data_htcj(cur_price, trade_time, create_time, update_time)
                VALUES (?,?,?,?);
            """.trimIndent()
                ) {
                    it.setString(1, nowPrice)
                    it.setString(2, time)
                    it.setString(3, now)
                    it.setString(4, now)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
//        val request = Request.Builder()
//            .get()
//            .header("Content-Type", "application/x-www-form-urlencoded")
//            .url("https://apis.tianapi.com/crude/index?key=5f1630a85072158742bf98d36ce15f31&code=wti")
//            .build()
//        val response = CLIENT.newCall(request).execute()
//        response.body?.bytes()?.let {
//
//            try {
//                val content = String(it, StandardCharsets.UTF_8)
//                val parseObject = JSON.parseObject(content)
//                val nowPrice = JSONPath.eval(parseObject, "$.result.nowprice") as BigDecimal
//                val updateTime = JSONPath.eval(parseObject, "$.result.updatetime") as String
//                val now = DateUtil.format(Date(), "yyyy-MM-dd HH:mm:ss")
//                executeInsert(
//                    """
//                insert into trade_data_tx(cur_price, trade_time, create_time, update_time)
//                VALUES (?,?,?,?);
//            """.trimIndent()
//                ) {
//                    it.setString(1, nowPrice.toString())
//                    it.setString(2, updateTime)
//                    it.setString(3, now)
//                    it.setString(4, now)
//                }
//            } catch (e: Exception) {
//                e.printStackTrace()
//            }
//        }

    }, 0, 1, TimeUnit.SECONDS)
//    val request: Request = Request.Builder()
//        .get()
//        .url(url)
//        .addHeader(
//            "User-Agent",
//            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36"
//        )
//        .build()
//    val factory = createFactory(CLIENT)
//    factory.newEventSource(request, object : EventSourceListener() {
//        override fun onClosed(eventSource: EventSource) {
//            super.onClosed(eventSource)
//        }
//
//        override fun onEvent(eventSource: EventSource, id: String?, type: String?, data: String) {
//            try {
//                val parseObject = JSON.parseObject(data)
//                val bigDecimal = JSONPath.eval(parseObject, "$.qt.p") as BigDecimal
//                val time = JSONPath.eval(parseObject, "$.qt.utime") as Int
//                val toLong = time.toLong() * 1000
//
//                val calendar = DateUtil.calendar(toLong)
//                val format = DateUtil.format(calendar.time, "yyyy-MM-dd HH:mm:ss")
//                val now = DateUtil.format(Date(), "yyyy-MM-dd HH:mm:ss")
//
//                println("${calendar.time} - $bigDecimal")
//
//                executeInsert(
//                    """
//                insert into trade_data_dfcf(cur_price, trade_time, create_time, update_time)
//                VALUES (?,?,?,?);
//            """.trimIndent()
//                ) {
//                    it.setString(1, bigDecimal.toString())
//                    it.setString(2, format)
//                    it.setString(3, now)
//                    it.setString(4, now)
//                }
//            } catch (e: Exception) {
//                e.printStackTrace()
//            }
//
//
//        }
//
//        override fun onFailure(eventSource: EventSource, t: Throwable?, response: Response?) {
//            super.onFailure(eventSource, t, response)
//        }
//
//        override fun onOpen(eventSource: EventSource, response: Response) {
//            super.onOpen(eventSource, response)
//        }
//    })
}